<template>
  <div class="departments-container">
    <div class="page-header">
      <h2 class="page-title">角色管理</h2>
      <el-button type="primary" v-permission="'role:create'" @click="handleAddRole">
        <el-icon><Plus /></el-icon>添加角色
      </el-button>
    </div>

    <el-card class="content-card">
      <el-row>
        <!-- 角色列表 -->
        <el-col :span="24">
          <!-- Search bar -->
          <div class="search-bar">
            <el-input
              v-model="searchQuery"
              placeholder="搜索角色名称或代码"
              clearable
              @clear="fetchRoleList"
              @keyup.enter="fetchRoleList"
            >
              <template #append>
                <el-button @click="fetchRoleList">
                  <el-icon><Search /></el-icon>
                </el-button>
              </template>
            </el-input>
          </div>

          <el-table
            v-loading="loading"
            :data="roleList"
            border
            style="width: 100%"
          >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="角色名称" />
        <el-table-column prop="code" label="角色代码" />
        <el-table-column prop="description" label="描述" />
        <el-table-column label="权限" width="300">
          <template #default="scope">
            <el-tooltip
              v-if="scope.row.permissions.length > 0"
              :content="getPermissionTooltipContent(scope.row.permissions)"
              placement="top"
              :hide-after="20"
            >
              <div class="permission-tag-container">
                <el-tag
                  v-for="perm in getVisiblePermissions(scope.row.permissions)"
                  :key="perm.id"
                  size="small"
                  class="permission-tag"
                  :type="getPermissionTagType(perm.code)"
                >
                  {{ perm.name }}
                </el-tag>
                <el-tag v-if="scope.row.permissions.length > 3" type="info" size="small">
                  +{{ scope.row.permissions.length - 3 }} 个权限
                </el-tag>
              </div>
            </el-tooltip>
            <span v-else>无权限</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280">
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              v-permission="'role:update'"
              @click="handleEditRole(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              size="small"
              type="success"
              v-permission="'role:update'"
              @click="handlePermissions(scope.row)"
            >
              权限设置
            </el-button>
            <el-button
              size="small"
              type="info"
              @click="handlePreviewRole(scope.row)"
            >
              预览
            </el-button>
            <el-button
              size="small"
              type="danger"
              v-permission="'role:delete'"
              @click="handleDeleteRole(scope.row)"
              :disabled="scope.row.code === 'admin'"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
                <div class="pagination-container">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 角色表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加角色' : '编辑角色'"
      width="500px"
    >
      <el-form
        ref="roleFormRef"
        :model="roleForm"
        :rules="roleFormRules"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" />
        </el-form-item>
        <el-form-item label="角色代码" prop="code">
          <el-input v-model="roleForm.code" :disabled="dialogType === 'edit'" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="roleForm.description"
            type="textarea"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitRoleForm">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 权限设置对话框 -->
    <el-dialog
      v-model="permissionDialogVisible"
      title="权限设置"
      width="800px"
      class="permission-dialog"
    >
      <div v-if="currentRole" class="permission-header">
        <span class="role-title">角色: {{ currentRole.name }}</span>
        <span class="role-code">({{ currentRole.code }})</span>
      </div>
      
      <el-input
        v-model="permissionSearchQuery"
        placeholder="搜索权限"
        clearable
        class="permission-search"
      />
      
      <el-tabs type="border-card" class="permission-tabs">
        <el-tab-pane v-for="(perms, category) in filteredGroupedPermissions" :key="category" :label="formatCategory(category)">
          <div class="category-actions">
            <el-button size="small" @click="selectAllInCategory(category)">全选</el-button>
            <el-button size="small" @click="unselectAllInCategory(category)">取消全选</el-button>
          </div>
          <el-checkbox-group v-model="selectedPermissions" class="permission-checkbox-group">
            <el-checkbox
              v-for="perm in perms" 
              :key="perm.id" 
              :label="perm.id"
              class="permission-checkbox"
            >
              <div class="permission-checkbox-content">
                <div class="permission-name">{{ perm.name }}</div>
                <div class="permission-code">{{ perm.code }}</div>
                <el-tooltip :content="perm.description" placement="top">
                  <el-icon><InfoFilled /></el-icon>
                </el-tooltip>
              </div>
            </el-checkbox>
          </el-checkbox-group>
        </el-tab-pane>
      </el-tabs>
      
      <div class="permission-summary">
        已选择 <span class="selected-count">{{ selectedPermissions.length }}</span> 个权限
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="permissionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="savePermissions">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 角色预览对话框 -->
    <el-dialog
      v-model="previewDialogVisible"
      title="角色权限预览"
      width="800px"
      class="preview-dialog"
    >
      <div v-if="currentRole" class="role-preview-header">
        <div class="role-info">
          <h3>{{ currentRole.name }} <span class="role-code">({{ currentRole.code }})</span></h3>
          <p v-if="currentRole.description">{{ currentRole.description }}</p>
        </div>
      </div>

      <div class="permission-visualization">
        <div class="role-circle">
          <div class="role-label">{{ currentRole?.name || '' }}</div>
        </div>
        <div class="permission-categories">
          <div 
            v-for="(perms, category) in rolePermissionsByCategory" 
            :key="category"
            class="category-container"
          >
            <div class="category-circle" :class="getCategoryColorClass(category)">
              <div class="category-label">{{ formatCategory(category) }}</div>
            </div>
            <div class="permissions-list">
              <div v-for="perm in perms" :key="perm.id" class="permission-item">
                <el-tag :type="getPermissionTagType(perm.code)" size="small" effect="dark">
                  {{ perm.name }}
                </el-tag>
                <div class="permission-code-preview">{{ perm.code }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <div v-if="!hasPermissions" class="no-permissions">
        该角色没有分配权限
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, InfoFilled } from '@element-plus/icons-vue'
import { useUserStore } from '../stores/user'
import { getRoleList, getPermissionList, createRole, updateRole, deleteRole } from '../api/user'
import { formatDateTime } from '../utils/format'

// 用户信息
const userStore = useUserStore()

// 角色列表数据
const loading = ref(false)
const roleList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const searchQuery = ref('')

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add') // 'add' 或 'edit'
const roleFormRef = ref(null)
const roleForm = reactive({
  id: '',
  name: '',
  code: '',
  description: ''
})

// 表单验证规则
const roleFormRules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入角色代码', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]+$/, message: '角色代码只能包含字母、数字和下划线', trigger: 'blur' }
  ]
}

// 权限设置相关
const permissionDialogVisible = ref(false)
const currentRole = ref(null)
const allPermissions = ref([])
const selectedPermissions = ref([])
const permissionSearchQuery = ref('')

// 预览相关
const previewDialogVisible = ref(false)
const rolePermissionsByCategory = ref({})
const hasPermissions = ref(true)

// 根据权限代码获取标签类型
const getPermissionTagType = (code) => {
  const prefix = code.split(':')[0]
  
  switch (prefix) {
    case 'user': return 'info'
    case 'role': return 'success'
    case 'permission': return 'warning'
    case 'rpa': return 'danger'
    case 'task': return 'info'
    case 'log': return 'warning'
    default: return 'info'
  }
}

// 获取前三个权限用于显示
const getVisiblePermissions = (permissions) => {
  return permissions.slice(0, 3)
}

// 生成权限工具提示内容
const getPermissionTooltipContent = (permissions) => {
  if (!permissions || permissions.length === 0) return '无权限'
  
  // 按类别分组权限
  const grouped = {}
  
  permissions.forEach(perm => {
    const category = perm.code.split(':')[0]
    if (!grouped[category]) {
      grouped[category] = []
    }
    grouped[category].push(perm.name)
  })
  
  // 生成工具提示文本
  let result = ''
  for (const category in grouped) {
    result += `${formatCategory(category)}：${grouped[category].join(', ')}\n`
  }
  
  return result.trim()
}

// 格式化权限类别名称
const formatCategory = (category) => {
  const categoryNames = {
    'user': '用户管理',
    'role': '角色管理',
    'permission': '权限管理',
    'department': '部门管理',
    'rpa': 'RPA管理',
    'task': '任务管理',
    'log': '日志管理'
  }
  
  return categoryNames[category] || category.charAt(0).toUpperCase() + category.slice(1)
}

// 获取角色列表
const fetchRoleList = async () => {
  loading.value = true
  try {
    // 构建请求参数
    const params = {
      page: currentPage.value,
      limit: pageSize.value,
      query: searchQuery.value.trim()
    }
    
    const response = await getRoleList(params)
    
    console.log('角色列表响应:', response)
    
    if (response && response.code === 200) {
      roleList.value = response.data.items
      total.value = response.data.total
    } else {
      ElMessage.error((response && response.message) || '获取角色列表失败')
    }
  } catch (error) {
    console.error('获取角色列表失败:', error)
    ElMessage.error('获取角色列表失败')
  } finally {
    loading.value = false
  }
}

// 获取所有权限
const fetchAllPermissions = async () => {
  try {
    const response = await getPermissionList({
      limit: 500 // 一次获取足够多的权限
    })
    
    console.log('权限列表响应:', response)
    
    if (response && response.code === 200) {
      allPermissions.value = response.data.items
    } else {
      ElMessage.error((response && response.message) || '获取权限列表失败')
    }
  } catch (error) {
    console.error('获取权限列表失败:', error)
    ElMessage.error('获取权限列表失败')
  }
}

// 添加角色
const handleAddRole = () => {
  dialogType.value = 'add'
  resetRoleForm()
  dialogVisible.value = true
}

// 编辑角色
const handleEditRole = (row) => {
  dialogType.value = 'edit'
  Object.assign(roleForm, {
    id: row.id,
    name: row.name,
    code: row.code,
    description: row.description || ''
  })
  dialogVisible.value = true
}

// 删除角色
const handleDeleteRole = (row) => {
  if (row.code === 'admin') {
    ElMessage.warning('超级管理员角色不能删除')
    return
  }
  
  ElMessageBox.confirm(
    `确定要删除角色 ${row.name} 吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const response = await deleteRole(row.id)
      
      if (response && response.code === 200) {
        ElMessage.success('删除成功')
        fetchRoleList() // 刷新角色列表
      } else {
        ElMessage.error((response && response.message) || '删除失败')
      }
    } catch (error) {
      console.error('删除角色失败:', error)
      ElMessage.error('删除角色失败')
    }
  }).catch(() => {})
}

// 打开权限设置对话框
const handlePermissions = (row) => {
  currentRole.value = row
  // 选中该角色拥有的权限
  selectedPermissions.value = row.permissions ? row.permissions.map(p => p.id) : []
  permissionDialogVisible.value = true
  
  // 确保已加载权限列表
  if (allPermissions.value.length === 0) {
    fetchAllPermissions()
  }
}

// 将权限按类别分组
const groupedPermissions = computed(() => {
  const groups = {}
  
  allPermissions.value.forEach(perm => {
    const parts = perm.code.split(':')
    const category = parts.length > 1 ? parts[0] : '其他'
    
    if (!groups[category]) {
      groups[category] = []
    }
    
    groups[category].push(perm)
  })
  
  return groups
})

// 过滤权限
const filteredGroupedPermissions = computed(() => {
  if (!permissionSearchQuery.value.trim()) {
    return groupedPermissions.value
  }
  
  const query = permissionSearchQuery.value.toLowerCase()
  const result = {}
  
  for (const category in groupedPermissions.value) {
    const filteredPerms = groupedPermissions.value[category].filter(perm => 
      perm.name.toLowerCase().includes(query) || 
      perm.code.toLowerCase().includes(query) ||
      perm.description?.toLowerCase().includes(query)
    )
    
    if (filteredPerms.length > 0) {
      result[category] = filteredPerms
    }
  }
  
  return result
})

// 全选类别中的所有权限
const selectAllInCategory = (category) => {
  const categoryPermIds = filteredGroupedPermissions.value[category].map(p => p.id)
  
  // 添加该类别所有权限ID到已选
  selectedPermissions.value = [...new Set([...selectedPermissions.value, ...categoryPermIds])]
}

// 取消全选类别中的所有权限
const unselectAllInCategory = (category) => {
  const categoryPermIds = filteredGroupedPermissions.value[category].map(p => p.id)
  
  // 从已选中移除该类别所有权限ID
  selectedPermissions.value = selectedPermissions.value.filter(id => !categoryPermIds.includes(id))
}

// 保存权限设置
const savePermissions = async () => {
  try {
    console.log('保存权限设置:', {
      roleId: currentRole.value.id,
      permissionIds: selectedPermissions.value
    })
    
    const response = await updateRole(currentRole.value.id, {
      permission_ids: selectedPermissions.value
    })
    
    console.log('保存权限响应:', response)
    
    if (response && response.code === 200) {
      ElMessage.success('权限设置已保存')
      permissionDialogVisible.value = false
      fetchRoleList() // 刷新角色列表
    } else {
      ElMessage.error((response && response.message) || '保存失败')
    }
  } catch (error) {
    console.error('保存权限设置失败:', error)
    ElMessage.error('保存权限设置失败')
  }
}

// 提交角色表单
const submitRoleForm = async () => {
  if (!roleFormRef.value) return
  
  await roleFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (dialogType.value === 'add') {
          // 新增角色
          const response = await createRole(roleForm)
          
          if (response && response.code === 200) {
            ElMessage.success('添加成功')
            dialogVisible.value = false
            fetchRoleList() // 刷新角色列表
          } else {
            ElMessage.error((response && response.message) || '添加失败')
          }
        } else {
          // 编辑角色
          const response = await updateRole(roleForm.id, roleForm)
          
          if (response && response.code === 200) {
            ElMessage.success('更新成功')
            dialogVisible.value = false
            fetchRoleList() // 刷新角色列表
          } else {
            ElMessage.error((response && response.message) || '更新失败')
          }
        }
      } catch (error) {
        console.error('提交角色数据失败:', error)
        ElMessage.error('提交失败')
      }
    }
  })
}

// 重置角色表单
const resetRoleForm = () => {
  if (roleFormRef.value) {
    roleFormRef.value.resetFields()
  }
  
  roleForm.id = ''
  roleForm.name = ''
  roleForm.code = ''
  roleForm.description = ''
}

// 分页相关
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchRoleList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchRoleList()
}

// 监听搜索关键字变化
watch(searchQuery, (newVal, oldVal) => {
  if (newVal !== oldVal && !newVal) {
    fetchRoleList()
  }
})

// 初始化
onMounted(() => {
  // 获取角色列表
  fetchRoleList()
  
  // 获取所有权限列表
  fetchAllPermissions()
})

// 预览角色
const handlePreviewRole = (row) => {
  currentRole.value = row
  // 获取角色权限并按类别分组
  rolePermissionsByCategory.value = {}
  hasPermissions.value = true
  
  if (row.permissions) {
    row.permissions.forEach(perm => {
      const category = perm.code.split(':')[0]
      if (!rolePermissionsByCategory.value[category]) {
        rolePermissionsByCategory.value[category] = []
      }
      rolePermissionsByCategory.value[category].push(perm)
    })
  } else {
    hasPermissions.value = false
  }
  
  previewDialogVisible.value = true
}

// 获取角色权限并按类别分组
const getRolePermissionsByCategory = (permissions) => {
  const grouped = {}
  
  permissions.forEach(perm => {
    const category = perm.code.split(':')[0]
    if (!grouped[category]) {
      grouped[category] = []
    }
    grouped[category].push(perm)
  })
  
  return grouped
}

// 获取类别颜色类
const getCategoryColorClass = (category) => {
  const categoryColors = {
    'user': 'success',
    'role': 'info',
    'permission': 'warning',
    'rpa': 'danger',
    'task': 'info',
    'log': 'warning'
  }
  
  return categoryColors[category] || 'default'
}
</script>

<style scoped>
.roles-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-bar {
  margin-bottom: 20px;
  max-width: 100%;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  align-items: center;
}

.content-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.permission-tag-container {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.permission-tag {
  margin-right: 0;
  margin-bottom: 0;
}

.permission-header {
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.role-title {
  font-weight: bold;
  font-size: 16px;
}

.role-code {
  color: #909399;
  margin-left: 8px;
}

.permission-search {
  margin-bottom: 16px;
}

.permission-tabs {
  margin-bottom: 16px;
  max-height: 400px;
  overflow-y: auto;
}

.permission-checkbox-group {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.permission-checkbox {
  width: calc(50% - 10px);
  margin-right: 0 !important;
  margin-left: 0 !important;
}

.permission-checkbox-content {
  display: flex;
  align-items: center;
  gap: 8px;
}

.permission-name {
  font-weight: 500;
}

.permission-code {
  color: #909399;
  font-size: 12px;
}

.category-actions {
  margin-bottom: 10px;
  text-align: right;
}

.permission-summary {
  margin-top: 16px;
  text-align: right;
  color: #606266;
}

.selected-count {
  font-weight: bold;
  color: #409EFF;
}

.role-preview-header {
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.role-info {
  margin-bottom: 10px;
}

.role-info h3 {
  font-weight: bold;
  font-size: 16px;
}

.role-code {
  color: #909399;
  margin-left: 8px;
}

.permission-visualization {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 0;
}

.role-circle {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  background-color: #409EFF;
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 30px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.role-label {
  font-weight: bold;
  font-size: 16px;
  text-align: center;
  padding: 10px;
}

.permission-categories {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 30px;
  width: 100%;
}

.category-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: calc(33.33% - 30px);
  min-width: 200px;
  margin-bottom: 30px;
}

.category-circle {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 15px;
  color: white;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.category-circle.success {
  background-color: #67c23a;
}

.category-circle.info {
  background-color: #909399;
}

.category-circle.warning {
  background-color: #e6a23c;
}

.category-circle.danger {
  background-color: #f56c6c;
}

.category-circle.default {
  background-color: #909399;
}

.category-label {
  font-weight: bold;
  font-size: 14px;
  text-align: center;
}

.permissions-list {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 10px;
  max-width: 100%;
}

.permission-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 10px;
}

.permission-code-preview {
  color: #909399;
  font-size: 11px;
  margin-top: 4px;
}

.no-permissions {
  text-align: center;
  margin-top: 20px;
  color: #909399;
  font-size: 16px;
  padding: 20px;
  background-color: #f8f8f8;
  border-radius: 4px;
}

.preview-dialog :deep(.el-dialog__body) {
  max-height: 600px;
  overflow-y: auto;
}
</style> 